<template>
    <div>
        <el-card shadow="never">
            <template slot="header">
                <span>部门列表</span>
            </template>
            <!-- 搜索 -->
            <el-form :model="searchForm" :inline="true" size="small" v-if="false">
                <el-form-item label="部门名称">
                    <el-input v-model="searchForm.deptName" placeholder="请输入部门名称" clearable style="width: 200px" />
                </el-form-item>
                <el-form-item label="状态">
                    <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 120px">
                        <el-option v-for="item in statusOptions" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleSearch">搜索</el-button>
                    <el-button @click="resetSearch">重置</el-button>
                </el-form-item>
            </el-form>

            <!-- 部门树形表格 -->
            <el-table :data="deptList" row-key="deptId" border
                :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" v-loading="loading"
                @selection-change="handleSelectionChange" style="width: 100%">
                <el-table-column type="selection" width="55" />
                <el-table-column prop="deptName" label="部门名称">
                    <template slot-scope="scope">
                        <span class="dept-name">{{ scope.row.deptName }}</span>
                    </template>
                </el-table-column>

                <el-table-column prop="orderNum" label="排序" align="center" />

                <el-table-column prop="status" label="状态" align="center">
                    <template slot-scope="scope">
                        <el-tag :type="getStatusTagType(scope.row.status)">
                            {{ getStatusText(scope.row.status) }}
                        </el-tag>
                    </template>
                </el-table-column>

                <el-table-column prop="createDate" label="创建时间" align="center">
                    <template slot-scope="scope">
                        {{ formatDate(scope.row.createDate) }}
                    </template>
                </el-table-column>

                <el-table-column label="操作" align="center" fixed="right">
                    <template slot-scope="scope" v-if="scope.row.parentId != 0">
                        <el-button type="text" size="small" @click="handleAdd(scope.row)" icon="el-icon-plus" v-auth="'add'">
                            新增子部门
                        </el-button>
                        <el-button type="text" size="small" @click="handleEdit(scope.row)" icon="el-icon-edit" v-auth="'edit'">
                            编辑
                        </el-button>
                        <el-button type="text" size="small" @click="handleDelete(scope.row)" icon="el-icon-delete" v-auth="'del'"
                            style="color: #f56c6c">
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
        <!-- 新增/编辑部门对话框 -->
        <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px" @close="resetForm" :close-on-click-modal="false">
            <el-form ref="deptForm" :model="deptForm" :rules="deptRules" label-width="100px" size="small">
                <el-form-item label="上级部门">
                    <el-select v-model="deptForm.parentId" placeholder="请选择上级部门" clearable style="width: 100%" disabled>
                        <el-option v-for="item in flatDeptOptions" :key="item.deptId" :label="item.displayName"
                            :value="item.deptId" />
                    </el-select>
                </el-form-item>

                <el-form-item label="部门名称" prop="deptName">
                    <el-input v-model="deptForm.deptName" placeholder="请输入部门名称" maxlength="50" show-word-limit />
                </el-form-item>

                <el-form-item label="排序" prop="orderNum">
                    <el-input-number v-model="deptForm.orderNum" :min="0" :max="999" placeholder="请输入排序号"
                        style="width: 100%" />
                </el-form-item>

                <el-form-item label="状态" prop="status" v-if="false">
                    <el-radio-group v-model="deptForm.status">
                        <el-radio label="NO">正常</el-radio>
                        <el-radio label="YES">停用</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitForm" :loading="submitLoading">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { getDeptTree, addDept, updateDept, deleteDept } from '../api/department'
import { statusOptions, statusTagType, statusText, formRules } from './options'

export default {
    name: 'DepartmentList',
    data() {
        return {
            // 搜索表单
            searchForm: {
                deptName: '',
                status: ''
            },

            // 部门列表数据
            deptList: [],

            // 部门选项（用于上级部门选择）
            deptOptions: [],

            // 选中的部门
            selectedDepts: [],

            // 加载状态
            loading: false,

            // 对话框相关
            dialogVisible: false,
            dialogTitle: '',
            submitLoading: false,

            // 部门表单
            deptForm: {
                deptId: null,
                parentId: null,
                deptName: '',
                orderNum: 0,
                // status: 'NO'
            },

            // 表单验证规则
            deptRules: formRules
        }
    },

    created() {
        this.getDeptList()
    },

    computed: {
        // 扁平化的部门选项，支持多级显示
        flatDeptOptions() {
            // const options = [{ deptId: 0, deptName: '顶级部门', displayName: '顶级部门' }]
            const options = []

            const flattenDepts = (depts, level = 0) => {
                depts.forEach(dept => {
                    const prefix = '　'.repeat(level) // 使用全角空格作为缩进
                    options.push({
                        ...dept,
                        displayName: `${prefix}${dept.deptName}`
                    })
                    if (dept.children && dept.children.length > 0) {
                        flattenDepts(dept.children, level + 1)
                    }
                })
            }

            flattenDepts(this.deptList)
            return options
        }
    },

    methods: {
        // 获取部门列表
        async getDeptList() {
            try {
                this.loading = true
                const response = await getDeptTree()
                this.deptList = response
                this.deptOptions = [...response]
                console.log(this.deptList, '获取部门列表');

            } catch (error) {
                this.$message.error('获取部门列表失败')
            } finally {
                this.loading = false
            }
        },

        // 搜索
        handleSearch() {
            this.getDeptList()
        },

        // 重置搜索
        resetSearch() {
            this.searchForm = {
                deptName: '',
                status: ''
            }
            this.getDeptList()
        },

        // 刷新数据
        refreshData() {
            this.getDeptList()
        },

        // 选择变化处理
        handleSelectionChange(selection) {
            this.selectedDepts = selection
        },

        // 批量删除
        handleBatchDelete() {
            if (this.selectedDepts.length === 0) {
                this.$message.warning('请选择要删除的部门')
                return
            }

            const deptNames = this.selectedDepts.map(dept => dept.deptName).join('、')
            this.$confirm(
                `确定要删除选中的部门"${deptNames}"吗？删除后不可恢复！`,
                '批量删除确认',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }
            ).then(async () => {
                try {
                    const promises = this.selectedDepts.map(dept => deleteDept(dept.deptId))
                    await Promise.all(promises)
                    this.$message.success('批量删除成功')
                    this.selectedDepts = []
                    this.getDeptList()
                } catch (error) {
                    console.error('批量删除失败:', error)
                }
            }).catch(() => {
                // 取消删除
            })
        },

        // 获取状态标签类型
        getStatusTagType(status) {
            return statusTagType[status] || 'info'
        },

        // 获取状态文本
        getStatusText(status) {
            return statusText[status] || '未知'
        },

        // 新增部门
        handleAdd(row) {
            this.dialogTitle = row ? '新增子部门' : '新增部门'
            this.deptForm = {
                deptId: null,
                parentId: row ? row.deptId : null,
                deptName: '',
                orderNum: 0,
                // status: 'NO'
            }
            this.dialogVisible = true
        },

        // 编辑部门
        handleEdit(row) {
            this.dialogTitle = '编辑部门'
            this.deptForm = {
                deptId: row.deptId,
                parentId: row.parentId,
                deptName: row.deptName,
                orderNum: row.orderNum,
                status: row.status
            }
            this.dialogVisible = true
        },

        // 删除部门
        handleDelete(row) {
            this.$confirm(
                `确定要删除部门"${row.deptName}"吗？删除后不可恢复！`,
                '删除确认',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }
            ).then(async () => {
                try {
                    const response = await deleteDept(row.deptId)
                    this.$message.success('删除成功')
                    this.getDeptList()
                } catch (error) {
                    console.error('删除部门失败:', error)
                    this.$message.error('删除部门失败')
                }
            }).catch(() => {
                // 取消删除
            })
        },

        // 提交表单
        submitForm() {
            this.$refs.deptForm.validate(async (valid) => {
                if (valid) {
                    try {
                        this.submitLoading = true
                        const api = this.deptForm.deptId ? updateDept : addDept
                        const response = await api(this.deptForm)
                        this.$message.success(this.deptForm.deptId ? '更新成功' : '添加成功')
                        this.dialogVisible = false
                        this.getDeptList()

                    } catch (error) {
                        console.error('操作失败:', error)
                    } finally {
                        this.submitLoading = false
                    }
                }
            })
        },

        // 重置表单
        resetForm() {
            this.$refs.deptForm && this.$refs.deptForm.resetFields()
            this.deptForm = {
                deptId: null,
                parentId: null,
                deptName: '',
                orderNum: 0,
                status: 'NO'
            }
        },

        // 格式化日期
        formatDate(date) {
            if (!date) return '-'
            return new Date(date).toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit'
            })
        }
    }
}
</script>

<style lang="scss" scoped>
.department-container {
    padding: 20px;

    .search-card {
        margin-bottom: 20px;
    }

    .table-card {
        .table-header {
            margin-bottom: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;

            .left-buttons {
                display: flex;
                gap: 10px;
            }

            .right-buttons {
                display: flex;
                gap: 10px;
            }
        }
    }

    .dept-name {
        font-weight: 500;
    }

    .dialog-footer {
        text-align: right;
    }
}
</style>